package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderOverViewVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServicelmpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private ShoppingCartServicelmpl shoppingCartServicelmpl;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    public OrderSubmitVO OrderSubmit(OrdersSubmitDTO ordersSubmitDTO) {
        //判断地址和购物车是否为空
        Long UserId = BaseContext.getCurrentId();
        BaseContext.removeCurrentId();
        if (ordersSubmitDTO.getAddressBookId() == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }


        //获取购物车所有数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.GetByUserid(UserId);
        if (shoppingCartList == null) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }


        //向Order表中插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));//使用时间戳作为订单编号
        orders.setUserId(UserId);
        orders.setOrderTime(LocalDateTime.now());
        AddressBook addressBook = addressBookMapper.getById(orders.getAddressBookId());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        orderMapper.InsertOrder(orders);//返回订单id
        //向Order_detail表插入N条购物车数据
        for (int i = 0; i < shoppingCartList.size(); i++) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCartList.get(i), orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderMapper.addDetail(orderDetail);
        }

        //下单成功后清空购物车
        shoppingCartMapper.clean(UserId);

        //封装OrderSubmitcVO返回
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        return orderSubmitVO;
    }


    /**
     * 用户支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public String pay(OrdersPaymentDTO ordersPaymentDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersPaymentDTO, orders);
        orders.setNumber(ordersPaymentDTO.getOrderNumber());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPayStatus(Orders.PAID);
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        Long orderId = orderMapper.getByNumberToId(orders);
        orderMapper.pay(orders);//修改状态
        String time = orderMapper.getByNumber(orders.getNumber());//获取预计送达时间


        //websocket发送来单提示
        Map<String, Object> map = new HashMap<>();
        map.put("type", 1);//1来单提示
        map.put("orderId", orderId);
        map.put("content", orders.getNumber());
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);

        return time;
    }


    /**
     * 历史订单查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public long CountOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        Long start = (long) ((ordersPageQueryDTO.getPage() - 1) * ordersPageQueryDTO.getPageSize());
        Long count = orderMapper.CountOrders(start, ordersPageQueryDTO);
        return count;
    }

    public List getOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        List<Orders> ordersList = new ArrayList<>();
        List<OrderVO> orderVOS = new ArrayList<>();
        Long start = (long) ((ordersPageQueryDTO.getPage() - 1) * ordersPageQueryDTO.getPageSize());
        ordersList = orderMapper.getOrders(start, ordersPageQueryDTO);
        for (int i = 0; i < ordersList.size(); i++) {
            OrderVO orderVO = new OrderVO();//OrderVo是Order的子类
            List<OrderDetail> orderDetailList = new ArrayList<>();
            orderDetailList = orderMapper.getOrderDetail(ordersList.get(i).getId());
            BeanUtils.copyProperties(ordersList.get(i), orderVO);
            orderVO.setOrderDetailList(orderDetailList);
            orderVOS.add(orderVO);
        }
        return orderVOS;
    }


    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    public OrderVO getOrderDetailById(Long id) {
        OrderVO orderVO = new OrderVO();
        orderVO = orderMapper.getOrdersById(id);
        List<OrderDetail> orderDetailList = new ArrayList<>();
        orderDetailList = orderMapper.getOrderDetail(id);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }


    /**
     * 用户端订单分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                log.info("拷贝后{} {}", orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }


    /**
     * 取消订单
     *
     * @param id
     * @return
     */
    public void cancel(Integer id) {
        orderMapper.cancel(Orders.CANCELLED, id, LocalDateTime.now());
    }


    /**
     * 再来一单
     *
     * @param id
     * @return
     */
    public void repetition(Integer id) {
        List<OrderDetail> orderDetailList = orderMapper.getByOrderId(Long.valueOf(id));
        for (int i = 0; i < orderDetailList.size(); i++) {
            ShoppingCartDTO shoppingCart = new ShoppingCartDTO();
            BeanUtils.copyProperties(orderDetailList.get(i), shoppingCart);
            shoppingCartServicelmpl.add(shoppingCart);
        }
    }


    /**
     * 统计各个状态订单数量
     *
     * @return
     */
    public OrderStatisticsVO CountOrderOver() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(orderMapper.CountToBeConfirmed(Orders.TO_BE_CONFIRMED));//待接单
        orderStatisticsVO.setConfirmed(orderMapper.CountConfirmed(Orders.CONFIRMED));//待派送
        orderStatisticsVO.setDeliveryInProgress(orderMapper.CountDeliveryInProgress(Orders.DELIVERY_IN_PROGRESS));//派送中
        return orderStatisticsVO;
    }


    /**
     * 接单
     *
     * @param id
     * @return
     */
    public void confirm(Long id) {
        orderMapper.confirm(Orders.CONFIRMED, id);
    }


    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     * @return
     */
    public void OrderCancel(OrdersCancelDTO ordersCancelDTO) {
        ordersCancelDTO.setStatus(Orders.CANCELLED);
        ordersCancelDTO.setCancelTime(LocalDateTime.now());
        orderMapper.AdminCancel(ordersCancelDTO);
    }


    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     * @return
     */
    public void OrdersRejectionI(OrdersRejectionDTO ordersRejectionDTO) {
        ordersRejectionDTO.setStatus(Orders.CANCELLED);
        ordersRejectionDTO.setCancelTime(LocalDateTime.now());
        orderMapper.OrdersRejection(ordersRejectionDTO);
    }


    /**
     * 订单派送
     *
     * @param id
     */
    public void delivery(Integer id) {
        Integer status = Orders.DELIVERY_IN_PROGRESS;
        orderMapper.delivery(status, id);
    }


    /**
     * 完成订单
     *
     * @param id
     * @return
     */
    public void complete(Integer id) {
        Integer status = Orders.COMPLETED;
        orderMapper.complete(id, status, LocalDateTime.now());
    }


}
